package com.fll.fangyigateway.loadblance;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class RoundLoadBalance implements LoadBalance {

    @Autowired
    private DiscoveryClient discoveryClient;
    private AtomicInteger atomicCount = new AtomicInteger(-1);

    @Override
    public ServiceInstance getInstances(String serviceId) {
        //查询出所有服务
        List<ServiceInstance> instances = discoveryClient.getInstances("fangyi-user");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        //轮询算法实现
        int index = atomicCount.incrementAndGet() % instances.size();

//        System.out.println(atomicCount.incrementAndGet() + "次数");

        return instances.get(index);
    }


}